<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>简易虚拟桌宠</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background: transparent;
            /* 允许点击穿透 */
            pointer-events: none;
        }

        /* 桌宠容器 */
        #petContainer {
            position: relative;
            width: 100%;
            height: 100%;
            pointer-events: auto; /* 桌宠区域可以点击 */
            cursor: move;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.1s ease;
        }

        #petContainer:hover {
            transform: scale(1.05);
        }

        /* 桌宠图片 */
        #petImage {
            display: block;
            width: 100%;
            height: 100%;
            user-select: none;
            -webkit-user-drag: none;
        }

        /* 关闭按钮样式 */
        #closeBtn {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 28px;
            height: 28px;
            background: rgba(255, 59, 48, 0.95);
            border: none;
            border-radius: 50%;
            color: white;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            pointer-events: auto;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
            opacity: 0;
            z-index: 10001;
        }

        #petContainer:hover #closeBtn {
            opacity: 1;
        }

        #closeBtn:hover {
            background: rgba(255, 59, 48, 1);
            transform: scale(1.2);
        }

        #closeBtn:active {
            transform: scale(0.9);
        }

        /* 当桌宠正在移动时，添加一个视觉指示 */
        #petContainer.moving {
            animation: subtle-pulse 2s ease-in-out infinite;
        }
        
        @keyframes subtle-pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.95; }
        }
    </style>
</head>
<body>
<!-- 桌宠容器 -->
<div id="petContainer">
    <button id="closeBtn" title="关闭桌宠">×</button>
    <img id="petImage" src="./assets/default-pet.svg" alt="桌宠">
</div>

<!-- 移除设置按钮，改用右键菜单和托盘图标 -->

<script>
    const { ipcRenderer } = require('electron');
    const path = require('path');
    const petContainer = document.getElementById('petContainer');
    const petImage = document.getElementById('petImage');
    const closeBtn = document.getElementById('closeBtn');

    // 屏幕尺寸（从主进程获取）
    let screenWidth = window.innerWidth;
    let screenHeight = window.innerHeight;

    // 配置
    let config = {
        pet: { size: 100, speed: 2, imagePath: './assets/default-pet.svg' },
        behavior: { autoMove: true, dragEnabled: true }
    };

    // 接收屏幕尺寸
    ipcRenderer.on('screen-size', (event, { width, height }) => {
        screenWidth = width;
        screenHeight = height;
        // 窗口已经在主进程中居中，获取当前窗口位置
        const { remote } = require('electron');
        try {
            const win = remote.getCurrentWindow();
            const [x, y] = win.getPosition();
            pet.windowX = x;
            pet.windowY = y;
        } catch (e) {
            // 如果remote不可用，使用默认位置
            pet.windowX = (screenWidth - pet.windowSize) / 2;
            pet.windowY = (screenHeight - pet.windowSize) / 2;
        }
    });

    // 接收暂停移动指令
    let manualPausedBySettings = false;
    ipcRenderer.on('pause-movement', (event, shouldPause) => {
        if (shouldPause) {
            manualPausedBySettings = true;
            wasMovingBeforeHover = pet.isMoving;
            pet.isMoving = false;
            petContainer.classList.remove('moving');
        } else {
            manualPausedBySettings = false;
            if (wasMovingBeforeHover && config.behavior?.autoMove !== false) {
                pet.isMoving = true;
                petContainer.classList.add('moving');
            }
        }
    });

    // 接收配置
    ipcRenderer.on('config-loaded', (event, newConfig) => {
        config = newConfig;
        
        // 更新图片（优先使用 URL，其次使用本地路径）
        if (config.pet?.useUrl && config.pet?.imageUrl) {
            // 使用 URL 图片
            petImage.src = config.pet.imageUrl;
            console.log('加载 URL 图片:', config.pet.imageUrl);
        } else if (config.pet?.imagePath) {
            // 使用本地图片
            petImage.src = config.pet.imagePath;
            console.log('加载本地图片:', config.pet.imagePath);
        }
        
        // 图片加载错误处理
        petImage.onerror = () => {
            console.error('图片加载失败，使用默认图片');
            petImage.src = './assets/default-pet.svg';
        };
        
        // 更新大小
        const size = config.pet?.size || 100;
        petContainer.style.width = `${size}px`;
        petContainer.style.height = `${size}px`;
        
        // 更新行为
        pet.speed = config.pet?.speed || 2;
        pet.isMoving = config.behavior?.autoMove !== false;
        
        // 添加移动类
        if (pet.isMoving) {
            petContainer.classList.add('moving');
        }
        
        console.log('配置已加载:', config);
    });

    // 关闭按钮点击事件
    closeBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        ipcRenderer.send('close-app');
    });

    // 移除了设置按钮，使用右键菜单和系统托盘代替

    // 桌宠属性（现在是整个窗口的位置）
    const pet = {
        windowX: 0, // 窗口在屏幕上的X坐标
        windowY: 0, // 窗口在屏幕上的Y坐标
        dx: 2, // X方向速度
        dy: 2, // Y方向速度
        isMoving: true, // 是否移动
        speed: 2,
        windowSize: 140 // 窗口大小
    };

    // 更新桌宠位置（通过移动窗口）
    function updatePet() {
        if (!pet.isMoving) return;

        // 更新窗口在屏幕上的位置
        pet.windowX += pet.dx * (pet.speed / 2);
        pet.windowY += pet.dy * (pet.speed / 2);

        // 碰到屏幕边缘反弹
        if (pet.windowX <= 0 || pet.windowX + pet.windowSize >= screenWidth) {
            pet.dx = -pet.dx;
            pet.windowX = Math.max(0, Math.min(pet.windowX, screenWidth - pet.windowSize));
        }
        if (pet.windowY <= 0 || pet.windowY + pet.windowSize >= screenHeight) {
            pet.dy = -pet.dy;
            pet.windowY = Math.max(0, Math.min(pet.windowY, screenHeight - pet.windowSize));
        }

        // 通知主进程移动窗口
        ipcRenderer.send('update-window-position', {
            x: pet.windowX,
            y: pet.windowY
        });
    }

    // 动画循环
    function animate() {
        updatePet();
        requestAnimationFrame(animate);
    }

    // 鼠标悬停事件：悬停时暂停移动
    let wasMovingBeforeHover = false;
    
    petContainer.addEventListener('mouseenter', () => {
        if (pet.isMoving) {
            wasMovingBeforeHover = true;
            pet.isMoving = false;
            petContainer.classList.remove('moving');
        }
    });
    
    petContainer.addEventListener('mouseleave', () => {
        if (wasMovingBeforeHover && config.behavior?.autoMove !== false) {
            setTimeout(() => {
                pet.isMoving = true;
                petContainer.classList.add('moving');
                wasMovingBeforeHover = false;
            }, 300);
        }
    });

    // 鼠标点击交互：左键切换移动状态
    petImage.addEventListener('click', (e) => {
        e.stopPropagation();
        pet.isMoving = !pet.isMoving;
        wasMovingBeforeHover = false; // 重置悬停状态
        
        // 视觉反馈
        if (pet.isMoving) {
            petContainer.classList.add('moving');
        } else {
            petContainer.classList.remove('moving');
        }
        
        petContainer.style.transform = pet.isMoving ? 'scale(1)' : 'scale(0.95)';
        setTimeout(() => {
            petContainer.style.transform = '';
        }, 200);
    });

    // 右键菜单
    petContainer.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        ipcRenderer.send('show-context-menu');
    });

    // 拖动功能（拖动整个窗口）
    let isDragging = false;
    let dragOffsetX, dragOffsetY;

    petContainer.addEventListener('mousedown', (e) => {
        if (e.target === closeBtn) return; // 点击关闭按钮时不触发拖动
        if (e.button === 2) return; // 右键点击时不触发拖动
        
        if (!config.behavior?.dragEnabled) return;
        
        isDragging = true;
        pet.isMoving = false; // 拖动时暂停自动移动
        
        // 记录鼠标相对于屏幕的位置
        dragOffsetX = e.screenX - pet.windowX;
        dragOffsetY = e.screenY - pet.windowY;
    });

    document.addEventListener('mousemove', (e) => {
        if (isDragging) {
            // 更新窗口位置
            pet.windowX = Math.max(0, Math.min(e.screenX - dragOffsetX, screenWidth - pet.windowSize));
            pet.windowY = Math.max(0, Math.min(e.screenY - dragOffsetY, screenHeight - pet.windowSize));
            
            // 通知主进程移动窗口
            ipcRenderer.send('update-window-position', {
                x: pet.windowX,
                y: pet.windowY
            });
        }
    });

    document.addEventListener('mouseup', () => {
        if (isDragging) {
            isDragging = false;
            // 拖动结束后恢复自动移动
            if (config.behavior?.autoMove !== false) {
                setTimeout(() => {
                    pet.isMoving = true;
                }, 500);
            }
        }
    });

    // 启动动画
    animate();
</script>
</body>
</html>
